<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        :key="showFormKey" v-if="showForm">
        <el-col :span="8" v-show="hasFormPermission('order_id')">
          <el-form-item :label="$t('对应销售合同')" prop="order_id">
            <el-select v-model="formData['order_id']" placeholder="请选择对应销售合同"
              :disabled="hasDisabledPermission('order_id',false)" filterable clearable
              :style="{width: '100%'}">
              <el-option v-for="(item, index) in order_idOptions" :key="index" :label="item.id"
                :value="item.id" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
		<el-col :span="24" v-show="hasFormPermission('order_id')">
		      <el-form-item :label="$t('联想弹层')" prop="order_id">
		        <el-input v-model="formData['order_id_showValue']" placeholder="请输入联想弹层"
		          :disabled="hasDisabledPermission('order_id',false)"
		          :readonly="!hasEditPermission('order_id',false)" clearable suffix-icon='el-icon-more'
		          :style="{width: '100%'}" @focus='autoHandlerClick(autoHandlerClickConfig(103))'
		          @clear="clearBombLayerFormData('order_id')"></el-input>
		        <el-form-item prop="order_id" style="display:none">
		          <el-input v-model="formData['order_id']"></el-input>
		        </el-form-item>
		      </el-form-item>
		    </el-col>
        <el-col :span="8" v-show="hasFormPermission('service_number')">
          <el-form-item :label="$t('服务编号')" prop="service_number">
            <el-input v-model="formData['service_number']" placeholder="请输入服务编号"
              :disabled="hasDisabledPermission('service_number',true)"
              :readonly="!hasEditPermission('service_number',true)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8" v-show="hasFormPermission('assembly_id')">
          <el-form-item :label="$t('组件名称')" prop="assembly_id">
            <el-input v-model="formData['assembly_id']" placeholder="请输入组件id"
              :disabled="hasDisabledPermission('assembly_id',false)"
              :readonly="!hasEditPermission('assembly_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('customer_id')">
          <el-form-item :label="$t('客户名称')" prop="customer_id">
            <el-input v-model="formData['customer_id']" placeholder="请输入客户id"
              :disabled="hasDisabledPermission('customer_id',false)"
              :readonly="!hasEditPermission('customer_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="4" v-show="hasFormPermission('customer_code')">
          <el-form-item :label="$t('客户编码')" prop="customer_code">
            <el-input v-model="formData['customer_code']" placeholder="请输入客户编码"
              :disabled="hasDisabledPermission('customer_code',false)"
              :readonly="!hasEditPermission('customer_code',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="4" v-show="hasFormPermission('contactor_id')">
          <el-form-item :label="$t('联系人id')" prop="contactor_id">
            <el-input v-model="formData['contactor_id']" placeholder="请输入联系人id"
              :disabled="hasDisabledPermission('contactor_id',false)"
              :readonly="!hasEditPermission('contactor_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('contactor_name')">
          <el-form-item :label="$t('联系人姓名')" prop="contactor_name">
            <el-input v-model="formData['contactor_name']" placeholder="请输入联系人姓名"
              :disabled="hasDisabledPermission('contactor_name',false)"
              :readonly="!hasEditPermission('contactor_name',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('contactor_phone')">
          <el-form-item :label="$t('联系人电话')" prop="contactor_phone">
            <el-input v-model="formData['contactor_phone']" placeholder="请输入联系人电话"
              :disabled="hasDisabledPermission('contactor_phone',false)"
              :readonly="!hasEditPermission('contactor_phone',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-show="hasLookFormPermission('field11233d8')">
          <el-form-item label-width="0" prop="field11233d8">
            <div style="border-top: 1px solid #dcdfe6;margin-top: 0px;margin-bottom: 0px;"></div>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('create_date')">
          <el-form-item :label="$t('订单签订日期')" prop="create_date">
            <el-date-picker :disabled="hasDisabledPermission('create_date',false)"
              :readonly="!hasEditPermission('create_date',false)" v-model="formData['create_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择订单签订日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="4" v-show="hasFormPermission('sales_department_id')">
          <el-form-item :label="$t('销售部门id')" prop="sales_department_id">
            <avue-load-tree v-model="formData['sales_department_id']"
              :disabled="hasDisabledPermission('sales_department_id',false)" placeholder="系统默认(公司)销售部门id"
              type="tree" :dic="sales_department_idOptions" :style="{width: '100%'}" :__type__="'department'">
            </avue-load-tree>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('sales_man_id')">
          <el-form-item :label="$t('销售方名称')" prop="sales_man_id">
            <xjr-select-user v-model="formData['sales_man_id']"
              :disabled="hasDisabledPermission('sales_man_id',false)" placeholder="请选择销售人员id"
              v-if="showForm" :userIds="formData.sales_man_id" @input="validateForm"></xjr-select-user>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-show="hasLookFormPermission('field1110760')">
          <el-form-item label-width="0" prop="field1110760">
            <div style="border-top: 1px solid #dcdfe6;margin-top: 0px;margin-bottom: 0px;"></div>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('contract_name')">
          <el-form-item :label="$t('销售合同名称')" prop="contract_name">
            <el-input v-model="formData['contract_name']" placeholder="请输入销售合同名称"
              :disabled="hasDisabledPermission('contract_name',false)"
              :readonly="!hasEditPermission('contract_name',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="hasFormPermission('contract_start_date')">
          <el-form-item :label="$t('服务开始日期')" prop="contract_start_date">
            <el-date-picker :disabled="hasDisabledPermission('contract_start_date',false)"
              :readonly="!hasEditPermission('contract_start_date',false)"
              v-model="formData['contract_start_date']" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{width: '100%'}" placeholder="请选择服务开始日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="hasFormPermission('contract_end_date')">
          <el-form-item :label="$t('服务结束日期')" prop="contract_end_date">
            <el-date-picker :disabled="hasDisabledPermission('contract_end_date',false)"
              :readonly="!hasEditPermission('contract_end_date',false)"
              v-model="formData['contract_end_date']" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
              :style="{width: '100%'}" placeholder="请选择服务结束日期" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="hasFormPermission('tax_amount')">
          <el-form-item :label="$t('含税金额')" prop="tax_amount">
            <el-input v-model.number="formData['tax_amount']" type="number" placeholder="请输入含税金额"
              :disabled="hasDisabledPermission('tax_amount',false)"
              :readonly="!hasEditPermission('tax_amount',false)" clearable :style="{width: '100%'}">
              <template slot="prepend">¥</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-show="hasFormPermission('none_tax_amount')">
          <el-form-item :label="$t('不含税金额')" prop="none_tax_amount">
            <el-input v-model.number="formData['none_tax_amount']" type="number" placeholder="请输入不含税金额"
              :disabled="hasDisabledPermission('none_tax_amount',false)"
              :readonly="!hasEditPermission('none_tax_amount',false)" clearable :style="{width: '100%'}">
              <template slot="prepend">¥</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('contract_instruction')">
          <el-form-item :label="$t('合同主要内容说明')" prop="contract_instruction">
            <el-input v-model="formData['contract_instruction']" type="textarea" placeholder="请输入合同主要内容说明"
              :disabled="hasDisabledPermission('contract_instruction',false)"
              :readonly="!hasEditPermission('contract_instruction',false)"
              :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('commentss')">
          <el-form-item :label="$t('其他说明')" prop="commentss">
            <el-input v-model="formData['commentss']" placeholder="请输入其他说明"
              :disabled="hasDisabledPermission('commentss',false)"
              :readonly="!hasEditPermission('commentss',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('files')">
          <el-form-item :label="$t('附件上传')" prop="files">
            <xjr-custom-upload :config="filesConfig" :disabled="hasDisabledPermission('files',false)"
              v-model="formData['files']" list-type="text"></xjr-custom-upload>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24" v-show="hasLookFormPermission('field122571c')">
          <el-form-item label-width="0" prop="field122571c">
            <div style="border-top: 1px solid #dcdfe6;margin-top: 0px;margin-bottom: 0px;"></div>
          </el-form-item>
        </el-col> -->
        <el-col :span="8" v-show="hasFormPermission('audit_state')" v-if="isedit">
          <el-form-item :label="$t('审阅结果')" prop="audit_state">
            <el-radio-group  v-model="formData['audit_state']" size="medium"
              :disabled="hasDisabledPermission('audit_state',false)"
              :readonly="!hasEditPermission('audit_state',undefined)">
              <el-radio v-for="(item, index) in audit_stateOptions" :key="index" :label="item.F_ItemValue"
                :disabled="item.disabled">{{item.F_ItemName}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('auditor_id')" v-if="isedit">
          <el-form-item :label="$t('审阅人')" prop="auditor_id">
            <el-input v-model="formData['auditor_id']" placeholder="请输入审阅人"
              :disabled="hasDisabledPermission('auditor_id',false)"
              :readonly="!hasEditPermission('auditor_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('audit_date')" v-if="isedit">
          <el-form-item :label="$t('审核日期')" prop="audit_date">
            <el-date-picker :disabled="hasDisabledPermission('audit_date',false)"
              :readonly="!hasEditPermission('audit_date',false)" v-model="formData['audit_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择审核日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('reject_reason')" v-if="isedit">
          <el-form-item :label="$t('不通过原因')" prop="reject_reason">
            <el-input v-model="formData['reject_reason']" placeholder="请输入不通过原因"
              :disabled="hasDisabledPermission('reject_reason',false)"
              :readonly="!hasEditPermission('reject_reason',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="6" v-show="hasFormPermission('contract_state')">
          <el-form-item label-width="0" prop="contract_state">
            <el-input v-model="formData['contract_state']" placeholder="请输入合同状态"
              :disabled="hasDisabledPermission('contract_state',false)"
              :readonly="!hasEditPermission('contract_state',false)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24" v-if="!isWorkflowForm">
          <el-form-item size="large" v-if="isEdit" class="form-button-center">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import workflowFormAuthorize from "@/mixins/workflowFormAuthorize";
        import authorizeMixin from "@/mixins/authorize";
        import nodeMsgMixin from "@/mixins/nodeMsg";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
        import {fieldsConfig,formFieldsMap,getHideComponents} from './service_contractConfig';
        import { formValidateNotice } from '@/util/util';		
        import store from "@/store";
        import hideComponentsMixin from "@/mixins/hideComponents"; // 隐藏组件
        export default {
          mixins: [authorizeMixin,workflowFormAuthorize,nodeMsgMixin,hideComponentsMixin],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    return {
      userInfo: {},
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
	  isedit:true,
      addressUrl:'service_contract',
      autoCompleteConfEventData: [],
      mainTableName: 'service_contract',
      formConfig: {},
      formFieldsMap: new Map(),
      hideComponentsMap: new Map(),
      needShowValueTags: ['asso-popup', 'mutiple-popup'],
	  autoCompleteConf: {},
      autoCompleteDialogVisible: false,
      formData: {
        'order_id': '',
		'order_id_showValue':'',
        'service_number': '',
        'assembly_id': '',
        'customer_id': '',
        'customer_code': '',
        'contactor_id': '',
        'contactor_name': '',
        'contactor_phone': '',
        'field11233d8': '',
        'create_date': null,
        'sales_department_id': '',
        'sales_man_id': '',
        'field1110760': '',
        'contract_name': '',
        'contract_start_date': null,
        'contract_end_date': null,
        'tax_amount': 0,
        'none_tax_amount': 0,
        'contract_instruction': '',
        'commentss': '',
        'files': null,
        'field122571c': '',
        'audit_state': '',
        'auditor_id': '',
        'audit_date': null,
        'reject_reason': '',
        'contract_state': '',
      },
      rules: {
        order_id: [{
          required: true,
          message: '请选择订单id',
          trigger: 'blur'
        }],
        service_number: [{
          required: true,
          message: '请输入服务编号',
          trigger: 'blur'
        }],
        assembly_id: [{
          required: true,
          message: '请输入组件id',
          trigger: 'blur'
        }],
        customer_id: [{
          required: true,
          message: '请输入客户id',
          trigger: 'blur'
        }],
        customer_code: [{
          required: true,
          message: '请输入客户编码',
          trigger: 'blur'
        }],
        contactor_id: [{
          required: true,
          message: '请输入联系人id',
          trigger: 'blur'
        }],
        contactor_name: [{
          required: true,
          message: '请输入联系人姓名',
          trigger: 'blur'
        }],
        contactor_phone: [{
          required: true,
          message: '请输入联系人电话',
          trigger: 'blur'
        }],
        create_date: [{
          required: true,
          message: '请选择订单签订日期',
          trigger: 'change'
        }],
        sales_department_id: [],
        sales_man_id: [],
        contract_name: [{
          required: true,
          message: '请输入销售合同名称',
          trigger: 'blur'
        }],
        contract_start_date: [{
          required: true,
          message: '请选择服务开始日期',
          trigger: 'change'
        }],
        contract_end_date: [{
          required: true,
          message: '请选择服务结束日期',
          trigger: 'change'
        }],
        tax_amount: [{
          required: true,
          message: '请输入含税金额',
          trigger: 'blur'
        }],
        none_tax_amount: [{
          required: true,
          message: '请输入不含税金额',
          trigger: 'blur'
        }],
        contract_instruction: [{
          required: true,
          message: '请输入合同主要内容说明',
          trigger: 'blur'
        }],
        commentss: [{
          required: true,
          message: '请输入其他说明',
          trigger: 'blur'
        }],
        files: [{
          required: true,
          message: '附件上传不能为空',
          trigger: 'change'
        }],
        audit_state: [{
          required: true,
          message: '审阅结果不能为空',
          trigger: 'change'
        }],
        auditor_id: [{
          required: true,
          message: '请输入审阅人',
          trigger: 'blur'
        }],
        audit_date: [{
          required: true,
          message: '请选择审核日期',
          trigger: 'change'
        }],
        reject_reason: [{
          required: true,
          message: '请输入不通过原因',
          trigger: 'blur'
        }],
        contract_state: [],
      },
      order_idOptions: [],
      sales_department_idOptions: undefined,
      sales_man_idOptions: undefined,
      filesConfig: {
        "showTip": false,
        "fileSize": 2,
        "sizeUnit": "MB",
        "buttonText": "点击上传",
        "disabled": false
      },
      audit_stateOptions: [],
      auditor_idOptions: undefined,
	  
    }
  },
  computed: {},
  watch: {
    'formData.tax_amount': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
    'formData.none_tax_amount': function(val, oldVal) {
      this.changeFormConfigDefaultValue();
    },
  },
  async created() {
    this.formConfig = this.getFormConfig();
    this.formFieldsMap = this.getFormFieldsMap();
    this.userInfo = localStorage.getItem("avue-userInfo") ? JSON.parse(localStorage.getItem(
      "avue-userInfo")).content : {};
  },
  async mounted() {
    this.hideComponentsMap = await this.getHideComponentsMap();
    this.showForm = false;
    await this.insertCreatedEvent();
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data
            
            if(res.data.data.audit_state){
                this.formData.audit_state = res.data.data.audit_state.split(',')
            }else{
              this.formData.audit_state = [];
            }
            
                  await this.handleEdit();
                 this.showFormKey++;
              } catch (error) {
              }
          }

       
    if (typeof this.getField100Options == "function") {
      await this.getField100Options();
    }
    if (typeof this.getField124Options == "function") {
      await this.getField124Options();
    }
	if (typeof this.getField104Options == "function" && this.operationVal == 'add') {
	  await this.getField104Options();
	}
    await this.insertMountedEvent();
    this.reRenderSubform = true; //子表单显示
    this.showFormKey++;
    this.processParameterAssignment();
    this.showForm = true;
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
      };
    },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
    async aysncValidateForm() {
      let validataArry = []
      let formValidateNotice = function formValidateNotice(obj, that, formAuth) {
        for (var o in obj) {
          if (!formAuth[o] && obj[o][0]) {
            that.$message({
              message: obj[o][0].message + ',' + that.$t('noFormAuth'),
              type: 'warning'
            });
            return;
          }
        }
      }
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid, object) => {
          if (!this.isWorkflowForm) formValidateNotice(object, this, this.formEnCodeList)
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {
      if (this.formData.audit_state instanceof Array) this.formData.audit_state = this.formData.audit_state
        .join(',')
    },
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();
      
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
      
      
      await this.handleSubmit();
    },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
	setModelValue(fields, autoBindFields, data) {
	      fields.map(item => {
	        if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
	          let childrenObj = item.__config__.childrenObj || {};
	          for (let key in childrenObj) {
	            let children = childrenObj[key];
	            this.setModelValue(children, autoBindFields, data);
	          }
	        }
	        else {
	          //找到对应formId 元素  key值为存储的对应formId
	          if (Object.prototype.toString.call(autoBindFields) === '[object Array]') {
	            autoBindFields.forEach(el => {
	              if (el.component == item.__config__.formId) {
	                this.formData[item.__vModel__] = data[el.bindField];
	              }
	            })
	          }
	          else {
	            if (autoBindFields.hasOwnProperty(item.__config__.formId)) {
	              //按绑定的自定义字段赋值
	              this.formData[item.__vModel__] = data[autoBindFields[item.__config__.formId]];
	            }
	          }
	        }
	      });
	      //更新表单校验
	      // this.validateForm();
	    },
    filterableCallBack(data) {
          if (!this.autoCompleteConf) {
            return false;
          }
          //弹窗关闭前回填数据  如果有选择数据项
          if (data) {
            let fields = this.getElements(this.formConfig.fields);
            let autoBindFields = this.autoCompleteConf.autoBindFields ? JSON.parse(this.autoCompleteConf
              .autoBindFields) : {};
            let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue' : this.autoCompleteConf
              .saveField;
            let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName' : this.autoCompleteConf
              .showField;
            this.setModelValue(this.formConfig.fields, autoBindFields, data);
            //自己赋值
            if (this.autoCompleteConf.dataType == 'dataItem') {
              for (let i = 0; i < fields.length; i++) {
                if (fields[i].__config__.formId == this.autoCompleteConf.formId) {
                  this.formData[this.autoCompleteConf.model] = data[saveField];
                  this.formData[this.autoCompleteConf.model + '_showValue'] = data[showField];
                  break;
                }
              }
            }
            else {
              this.formData[this.autoCompleteConf.model] = data[saveField];
              this.formData[this.autoCompleteConf.model + '_showValue'] = data[showField];
            }
          }
          if (this.autoCompleteConfEventData && this.autoCompleteConfEventData.length > 0) {
            this.triggerEventHandler(this.autoCompleteConfEventData);
          }
          //关闭弹窗
          this.autoCompleteDialogVisible = false;
        },
		
          //辅助编辑 预留方法
          async handleEdit() {
            await this.insertEditEvent();
          },
    getElements(fields) {
              let _arr = [];
              fields.map(item => {
                if (item.__config__.componentName == 'avue-tabs') {
                  let childrenObj = item.__config__.childrenObj || {};
                  for (let key in childrenObj) {
                    _arr.push(...this.getElements(childrenObj[key]));
                  }
                }
                else {
                  _arr.push(item);
                }
              });
              return (() => {
                return _arr;
              })();
            },  
	autoHandlerClick(conf) {
	      if (conf.eventData && conf.eventData.length > 0) {
	        this.autoCompleteConfEventData = conf.eventData;
	      }
	      else {
	        this.autoCompleteConfEventData = conf.eventData;
	      }
	      this.autoCompleteConf.title = conf.label + '-选择记录';
	      this.autoCompleteConf.model = conf.model;
	      this.autoCompleteConf.formId = conf.formId;
	      this.autoCompleteConf.dataType = conf.dataType;
	      switch (conf.dataType) {
	      case 'dataSource':
	        this.autoCompleteConf.dataSource = conf.dataSource;
	        this.autoCompleteConf.tabName = 'base';
	        break;
	      case 'dataSql':
	        this.autoCompleteConf.dataSource = conf.database;
	        this.autoCompleteConf.tabName = 'sql';
	        this.autoCompleteConf.sqlStr = conf.sql;
	        break;
	      case 'dataItem':
	        this.autoCompleteConf.dataSource = conf.dataItem;
	        this.autoCompleteConf.dataItem = conf.dataItem;
	        this.autoCompleteConf.fields = ['F_ItemName', 'F_ItemValue'];
	        break;
	      case 'dataApi':
	        this.autoCompleteConf.apiConfig = conf.apiConfig;
	        this.autoCompleteConf.formFieldsMap = this.formFieldsMap;
	        this.autoCompleteConf.formData = this.formData;
	        this.autoCompleteConf.tabName = 'api';
	        break;
	        conf.showField = 'F_ItemName';
	        conf.saveField = 'F_ItemValue';
	        this.autoCompleteConf.tabName = 'item';
	        break;
	      }
	      this.autoCompleteConf.showField = conf.showField;
	      this.autoCompleteConf.saveField = conf.saveField;
	      this.autoCompleteConf.autoBindFields = conf.autoBindFields;
	      this.autoCompleteConf.defaultValue = this.formData[conf.model];
	      this.autoCompleteDialogVisible = true;
	    },
	
    
        //辅助提交 预留方法
        async handleSubmit() {
          await this.insertSubmitEvent();
        },
        //辅助工作流提交 预留方法
        getHandleSubmitFormEvent() {
            
        },
        //辅助工作流表单事件 判断 表单事件是否已经执行过
        getisExecutedFormEvent() {
            let key = 'index'+this.$store.state.formParser.workflowFormTabIndexKey;
            return this.$store.state.formParser.isExecutedFormEvent[key]?this.$store.state.formParser.isExecutedFormEvent[key]:false;
            
        },
      
    getNumberFixed2(number) {
      let splitNum = ("" + number).replace(/(^0*)/g, "").split(".");
      let num = splitNum[0] == "" ? '0' : splitNum[0];
      if (splitNum.length > 1) {
        num += '.';
        let roundNum = 2; //保留两位小数
        for (let i = 0; i < roundNum; i++) {
          num += splitNum[1][i];
        }
      }
      return parseFloat(num);
    },
    changeFormConfigDefaultValue() {
      let valueForFormIdMap = new Map();
      this.formConfig.fields.forEach((ele) => {
        if (ele.__config__.componentName == "table") {
          ele.__config__.children.forEach((element) => {
            valueForFormIdMap.set(ele.__config__.formId + "-table-" + element.__config__.formId,
              element.__config__.defaultValue);
          });
        }
        else if (ele.__config__.componentName && ele.__config__.componentName == 'avue-tabs') {
          let childrenObj = ele.__config__.childrenObj || {};
          let _arr = this.getValByTabs(childrenObj);
          _arr.map(item => {
            valueForFormIdMap.set(item.formId, item.defaultValue);
          });
        }
        else {
          valueForFormIdMap.set(ele.__config__.formId, this.formData[ele.__vModel__]);
        }
      });
      this.formConfig.fields.forEach((ele, index) => {
        if (ele.__config__.componentName == "table") {
          ele.__config__.children.forEach((element, childrenIndex) => {
            let defaultValue = 0;
            if (element.computationalConfiguration && element.computationalConfiguration.length > 0) {
              let formulaStr = "";
              element.computationalConfiguration.forEach((item) => {
                if (item.type == "taxRate") {
                  //税率
                  if (element.taxRate >= 0) {
                    formulaStr += element.taxRate * 0.01;
                  }
                }
                else {
                  let eleValue = valueForFormIdMap.get(item.formId) || 0;
                  formulaStr += item.formId == 0 ? item.name : eleValue;
                }
              });
              defaultValue = eval(formulaStr) * 100;
              defaultValue = this.getNumberFixed2(defaultValue) / 100;
              //大写
              if (element.isCapitalized) {
                this.formConfig.fields[index].__config__.children[childrenIndex].__config__
                  .capitalizedValue = this.getCapitalizedMethod(defaultValue);
              }
              this.formConfig.fields[index].__config__.children[childrenIndex].__config__
                .defaultValue = defaultValue;
              this.formData[element.__vModel__] = defaultValue;
            }
          });
        }
        else if (ele.__config__.componentName && ele.__config__.componentName == 'avue-tabs') {
          let childrenObj = ele.__config__.childrenObj || {};
          //avue-tabs
          this.calcDefaultValueByTabs(ele.__config__.childrenObj, valueForFormIdMap);
        }
        else {
          let defaultValue = 0;
          if (ele.computationalConfiguration && ele.computationalConfiguration.length > 0) {
            let formulaStr = "";
            ele.computationalConfiguration.forEach((item) => {
              if (item.type == "taxRate") {
                //税率
                if (ele.taxRate >= 0) {
                  formulaStr += ele.taxRate * 0.01;
                }
              }
              else {
                let eleValue = valueForFormIdMap.get(item.formId) || 0;
                formulaStr += item.formId == 0 ? item.name : eleValue;
              }
            });
            defaultValue = eval(formulaStr) * 100;
            defaultValue = this.getNumberFixed2(defaultValue) / 100;
            //大写
            if (ele.isCapitalized) {
              this.formConfig.fields[index].__config__.capitalizedValue = this.getCapitalizedMethod(
                defaultValue);
            }
            this.formConfig.fields[index].__config__.defaultValue = defaultValue;
            this.formData[ele.__vModel__] = defaultValue;
          }
        }
      });
    },
    getValByTabs(childrenObj) {
      let _arr = [];
      if (!childrenObj || !(childrenObj instanceof Object)) return [];
      for (let key in childrenObj) {
        let children = childrenObj[key];
        children.map(item => {
          if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
            let cObj = item.__config__.childrenObj || {};
            _arr.push(...this.getValByTabs(item.__config__.childrenObj));
          }
          else {
            let _obj = {};
            _obj.formId = item.__config__.formId;
            _obj.defaultValue = this.formData[item.__vModel__];
            _arr.push(_obj);
          }
        });
      }
      return (() => {
        return _arr;
      })()
    },
    calcDefaultValueByTabs(childrenObj, valueForFormIdMap) {
      if (!childrenObj || !(childrenObj instanceof Object)) return;
      for (let key in childrenObj) {
        let children = childrenObj[key];
        children.map(item => {
          if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
            let cObj = item.__config__.childrenObj || {};
            this.calcDefaultValueByTabs(cObj, valueForFormIdMap);
          }
          else {
            let defaultValue = 0;
            if (item.computationalConfiguration && item.computationalConfiguration.length > 0) {
              let formulaStr = "";
              item.computationalConfiguration.forEach((c) => {
                if (c.type == "taxRate") {
                  //税率
                  if (item.taxRate >= 0) {
                    formulaStr += item.taxRate * 0.01;
                  }
                }
                else {
                  let eleValue = valueForFormIdMap.get(c.formId) || 0;
                  formulaStr += c.formId == 0 ? c.name : eleValue;
                }
              });
              defaultValue = eval(formulaStr) * 100;
              defaultValue = this.getNumberFixed2(defaultValue) / 100;
              item.__config__.defaultValue = defaultValue;
              this.formData[item.__vModel__] = defaultValue;
            }
          }
        });
      }
    },
    async getField100Options() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/data-sources/088300080f8054153a7cd61e7a22cdb2/data',
        });
        let {
          data
        } = resp.data;
        let tempData = [];
        if (data && data.length > 0) {
          tempData = data.map(ele => {
            if ('id') {
              ele['id'] = ele['id'] + '';
            }
            return ele
          });
        }
        this.order_idOptions = tempData
      }
      catch (error) {}
    },
    async getField124Options() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/data-items/SHJG/detail',
        });
        if (resp.data.data) {
          this.audit_stateOptions = resp.data.data;
        }
      }
      catch (error) {}
    },
	async getField104Options() {
	  // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
	  try {
	    let resp = await this.$axios({
	      method: 'get',
	      url:  baseUrl + '/code-rules/ServiceContractCode/gen',
	    });
	    if (resp.data.data) {
	      this.formData.service_number = resp.data.data;
	    }
	  }
	  catch (error) {}
	},
    async triggerEventHandler(eventData) {
      if (eventData.length > 0) {
        eventData.forEach(ele => {
          let functionName = 'getField' + ele.componentFormId + 'Options';
          if (typeof this[functionName] == "function") {
            this[functionName]();
          }
        })
      }
    },
    triggerEventFormIdHandler(formId) {
      if (this.formFieldsMap.get(formId).__config__.triggerEvents && this.formFieldsMap.get(formId).__config__
        .triggerEvents.length > 0) {
        this.formFieldsMap.get(formId).__config__.triggerEvents.forEach(triggerEventItem => {
          if (this.formFieldsMap.get(formId).__config__.triggerEventData && this.formFieldsMap.get(formId)
            .__config__.triggerEventData[triggerEventItem] && this.formFieldsMap.get(formId).__config__
            .triggerEventData[triggerEventItem].length > 0) {
            this.triggerEventHandler(this.formFieldsMap.get(formId).__config__.triggerEventData[
              triggerEventItem]);
          }
        });
      }
      return true;
    },
    //清空联想弹层、多选弹层的值
    clearBombLayerFormData(filed) {
      this.formData[filed] = '';
      this.formData[filed + '_showValue'] = '';
    },
    // 流程参数赋值
    processParameterAssignment() {
      // 流程中的流程参数赋值 优先级最高，最后赋值
      setTimeout(() => {
        if (this.isEdit != 2 && this.parameter && this.parameter[this.mainTableName]) {
          this.showForm = false;
          for (let [key, value] of Object.entries(this.parameter[this.mainTableName])) {
            this.setFormDataValue(key, value);
          }
          this.showForm = true;
        }
      }, 0);
    },
    setFormDataValue(field, val) {
      if (Array.isArray(this.formData[field])) {
        if (val.includes(',')) {
          this.formData[field] = val.split(',');
        }
        else {
          this.formData[field] = [val];
        }
      }
      else {
        this.formData[field] = val;
      }
      //处理联想弹层，多选弹层
      if (this.formData[field + '_showValue'] != undefined) {
        this.formData[field + '_showValue'] = val;
      }
    },
    setOutputsValue(nodeType, formId, res, outputKey) {
      let nodeTypeChecked = false;
      if (nodeType == 'created') {
        nodeTypeChecked = this.operationVal == 'add';
      }
      else if (nodeType == 'edit') {
        nodeTypeChecked = this.operationVal == 'edit';
      }
      else if (nodeType == 'mounted') {
        nodeTypeChecked = this.operationVal == 'add' || this.operationVal == 'edit';
      }
      if (nodeTypeChecked && this.disabled != true && res && res.data && res.data.data && this.formFieldsMap
        .has(formId) && this.formFieldsMap.get(formId).__vModel__ && this.formData.hasOwnProperty(this
          .formFieldsMap.get(formId).__vModel__)) {
        this.setFormDataValue(this.formFieldsMap.get(formId).__vModel__, res.data.data[outputKey]);
        // 联想弹层 多选弹层 特殊处理
        if (this.formFieldsMap.get(formId).__config__ && this.formFieldsMap.get(formId).__config__.avueType &&
          this.needShowValueTags.includes(this.formFieldsMap.get(formId).__config__.avueType)) {
          this.formData[this.formFieldsMap.get(formId).__vModel__ + '_showValue'] = res.data.data[outputKey];
        }
        this.triggerEventFormIdHandler(formId);
      }
    },
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList && this.formSubTableNotRequiredList[bindTable] !=
                undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList && this.formSubTableDisabledList[bindTable] !=
                undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
              if (this.disabled) { //查看
                ele2.disabled = true;
              }
            }
            else {
              ele2.rules = []
              if (ele2.required) {
                ele2.ruleList.forEach(el => {
                  el.message += ',' + this.$t('noFormAuth')
                })
                ele2.rules = ele2.ruleList;
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    async insertCreatedEvent() {
      
    },
    async insertMountedEvent() {
      
    },
    async insertEditEvent() {
      
    },
    async insertSubmitEvent() {
      
    },
    getFormConfig() {
       return fieldsConfig();
    },
    getFormFieldsMap() {
       return formFieldsMap();
    },
    async getHideComponentsMap() {
      let mapList = new Map();
      let hideComponentList = this.getHideComponents();
      if (typeof this.initHideComponentList == 'function') {
        mapList = await this.initHideComponentList(hideComponentList);
        this.$store.commit("SET_HIDE_COMPONENT_LIST", mapList);
      }
      return mapList;
    },
    getHideComponentsMapItem(key) {
      if (this.hideComponentsMap.size > 0) {
        return this.hideComponentsMap.has(key) ? this.hideComponentsMap.get(key) : "";
      }
      else {
        return ""
      }
    },
    getHideComponents() {
       return getHideComponents();
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

.el-upload__tip {
  line-height: 1.2;
}

</style>
